<template>
  <div class="map-page">
    <!-- 顶部控制区 -->
    <div class="header">
      <h2>出行轨迹（腾讯地图版）</h2>
      <div class="controls">
        <button @click="startTracking" :disabled="isTracking">开始记录</button>
        <button @click="stopTracking" :disabled="!isTracking">停止记录</button>
        <button @click="showDemoTrack">显示演示轨迹</button>
        <button @click="clearTrack">清空轨迹</button>
        <button @click="centerToCurrent">定位到当前位置</button>
      </div>
    </div>

    <!-- 地图容器 -->
    <div id="map"></div>

    <!-- 信息面板 -->
    <div class="info-panel" v-if="trackPoints.length > 0">
      <div class="info-item">
        <span>轨迹点数:</span>
        <span>{{ trackPoints.length }}</span>
      </div>
      <div class="info-item">
        <span>总距离:</span>
        <span>{{ totalDistance.toFixed(2) }} 米</span>
      </div>
      <div class="info-item">
        <span>记录时长:</span>
        <span>{{ formatDuration }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'

let map = null
let trackPoints = ref([])
let polyline = null
let marker = null
let watchId = null
let startTime = null
let isTracking = ref(false)
let totalDistance = ref(0)
const formatDuration = ref('00:00:00')

// 演示轨迹
const demoTrackPoints = [
  { lat: 39.915, lng: 116.404 },
  { lat: 39.914, lng: 116.406 },
  { lat: 39.913, lng: 116.408 },
  { lat: 39.912, lng: 116.410 },
  { lat: 39.911, lng: 116.412 },
  { lat: 39.910, lng: 116.415 },
  { lat: 39.909, lng: 116.418 },
  { lat: 39.908, lng: 116.420 },
  { lat: 39.907, lng: 116.422 },
  { lat: 39.906, lng: 116.424 }
]

onMounted(async () => {
  await nextTick()
  initMap()
  // 禁止页面滚动
  document.body.style.overflow = 'hidden'
})

onBeforeUnmount(() => {
  stopTracking()
  document.body.style.overflow = ''
})

// 初始化地图
function initMap() {
  setTimeout(() => {
    if (typeof TMap === 'undefined') {
      console.error('TMap SDK 未加载，请检查 key')
      return
    }

    const mapDiv = document.getElementById('map')
    if (!mapDiv) return

    map = new TMap.Map(mapDiv, {
      center: new TMap.LatLng(39.915, 116.404),
      zoom: 14,
      pitch: 0,
      rotation: 0
    })

    // 延迟调整防止自动滚动
    setTimeout(() => {
      map.resize()
      window.scrollTo(0, 0)
    }, 500)

    console.log('腾讯地图初始化完成')
  }, 300)
}

// 显示演示轨迹
function showDemoTrack() {
  clearTrack()
  const points = demoTrackPoints.map(c => new TMap.LatLng(c.lat, c.lng))
  trackPoints.value = points.map(p => ({ latLng: p, timestamp: new Date() }))
  drawPolyline(points)
  addMarker(points[0], '起点')
  addMarker(points[points.length - 1], '终点')
  totalDistance.value = 5800
  formatDuration.value = '00:45:30'
  map.fitBounds(new TMap.LatLngBounds(points[0], points[points.length - 1]))
}

function drawPolyline(points) {
  if (polyline) polyline.setMap(null)
  polyline = new TMap.MultiPolyline({
    map,
    geometries: [{ paths: points, color: '#1890ff', width: 6, borderColor: '#0066ff', borderWidth: 2 }]
  })
}

function addMarker(latLng, title) {
  const layer = new TMap.MultiMarker({
    map,
    geometries: [{ position: latLng, properties: { title } }]
  })
  return layer
}

function startTracking() {
  if (isTracking.value) return
  isTracking.value = true
  trackPoints.value = []
  totalDistance.value = 0
  startTime = new Date()

  if (!navigator.geolocation) {
    alert('浏览器不支持定位')
    isTracking.value = false
    return
  }

  watchId = navigator.geolocation.watchPosition(
      pos => {
        const { latitude, longitude } = pos.coords
        const latLng = new TMap.LatLng(latitude, longitude)
        trackPoints.value.push({ latLng, timestamp: new Date() })
        drawPolyline(trackPoints.value.map(p => p.latLng))
        if (marker) marker.setMap(null)
        marker = addMarker(latLng, '当前位置')
        map.setCenter(latLng)
        updateDistanceAndTime()
      },
      err => {
        console.error('定位失败:', err)
        alert('定位失败，请检查权限')
        isTracking.value = false
      },
      { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
  )
}

function updateDistanceAndTime() {
  if (trackPoints.value.length >= 2) {
    let dist = 0
    for (let i = 1; i < trackPoints.value.length; i++) {
      dist += TMap.geometry.computeDistance(trackPoints.value[i - 1].latLng, trackPoints.value[i].latLng)
    }
    totalDistance.value = dist
  }
  if (startTime) {
    const sec = Math.floor((new Date() - startTime) / 1000)
    const h = String(Math.floor(sec / 3600)).padStart(2, '0')
    const m = String(Math.floor((sec % 3600) / 60)).padStart(2, '0')
    const s = String(sec % 60).padStart(2, '0')
    formatDuration.value = `${h}:${m}:${s}`
  }
}

function stopTracking() {
  if (!isTracking.value) return
  isTracking.value = false
  if (watchId) {
    navigator.geolocation.clearWatch(watchId)
    watchId = null
  }
}

function clearTrack() {
  stopTracking()
  trackPoints.value = []
  totalDistance.value = 0
  formatDuration.value = '00:00:00'
  if (polyline) polyline.setMap(null)
  if (marker) marker.setMap(null)
}

function centerToCurrent() {
  if (!navigator.geolocation) return alert('浏览器不支持定位')
  navigator.geolocation.getCurrentPosition(
      pos => {
        const { latitude, longitude } = pos.coords
        const latLng = new TMap.LatLng(latitude, longitude)
        map.setCenter(latLng)
        map.setZoom(17)
        if (marker) marker.setMap(null)
        marker = addMarker(latLng, '当前位置')
      },
      err => alert('定位失败'),
      { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
  )
}
</script>

<style scoped>
/* ======= 防止地图推动页面滚动 ======= */
html, body {
  margin: 0;
  padding: 0;
  overflow: hidden; /* 关键：禁止滚动条 */
}

/* 页面结构固定布局 */
.map-page {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

/* 顶部区域固定 */
.header {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  background: #f5f5f5;
  border-bottom: 1px solid #ddd;
  z-index: 10;
  padding: 8px 10px;
}
.header h2 {
  margin: 0 0 6px 0;
  font-size: 16px;
}
.controls {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
.controls button {
  padding: 6px 12px;
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
}
.controls button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 地图区域绝对定位填满剩余空间 */
#map {
  position: absolute;
  top: 80px; /* header 高度 */
  bottom: 60px; /* info-panel 高度 */
  left: 0;
  right: 0;
  width: 100%;
}

/* 信息面板固定在底部 */
.info-panel {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(245, 245, 245, 0.95);
  border-top: 1px solid #ddd;
  display: flex;
  justify-content: space-around;
  padding: 6px 0;
  z-index: 10;
}
.info-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 13px;
}
.info-item span:last-child {
  font-weight: bold;
}
</style>
